extern crate winapi;

use std::ptr::null_mut;
use std::os::raw::c_void;
use winapi::ctypes::{c_int, wchar_t};
use winapi::shared::minwindef::{LPARAM, WPARAM};
use winapi::shared::windef::HWND;
use winapi::um::{
    libloaderapi,
    winuser::{
    CallNextHookEx, MSLLHOOKSTRUCT, SetWindowsHookExW, UnhookWindowsHookEx, WH_MOUSE_LL,
    }
};

type HOOKPROC = Option<unsafe extern "system" fn(ncode: c_int, wparam: WPARAM, lparam: LPARAM) -> c_int>;

extern "system" fn mouse_hook(ncode: c_int, wparam: WPARAM, lparam: LPARAM) -> c_int {
    if ncode >= 0 {
        unsafe {
            let mouse_struct: &MSLLHOOKSTRUCT = &*(lparam as *const MSLLHOOKSTRUCT);
            // 这里可以访问鼠标的位置和点击事件
            println!("Mouse at x: {}, y: {}", mouse_struct.pt.x, mouse_struct.pt.y);
            
            // 如果需要控制鼠标，可以在这里实现，例如阻止鼠标移动或点击
            // 例如，如果我们要阻止这次鼠标移动，则返回1
            if wparam == winapi::um::winuser::WM_MOUSEMOVE {
                return 1;
            }
        }
    }
    unsafe { CallNextHookEx(null_mut(), ncode, wparam, lparam) }
}

fn main() {
    let hinstance = unsafe { winapi::um::libloaderapi::GetModuleHandleW(null_mut()) };
    let hook = unsafe {
        SetWindowsHookExW(WH_MOUSE_LL, Some(mouse_hook) as HOOKPROC, hinstance, 0)
    };

    if hook.is_null() {
        eprintln!("Failed to set hook.");
        return;
    }

    println!("Mouse hook is set. Press Enter to exit...");
    std::io::stdin().read_line(&mut String::new()).unwrap();

    unsafe {
        UnhookWindowsHookEx(hook);
    }

    println!("Mouse hook has been removed.");
}